import { AirdropModalOptions, CountdownInfo, StateType, ThemeConfig, CheckResult, ModalStatus, TemplateData } from './types';
import { DEFAULT_THEMES } from './types';
import { baseStyles, fontsImport } from './styles';
import { modalTemplate } from './templates';
import { createElement, deepMerge, formatNumber, hexToRgb, injectCSS, isMobileDevice, shadeColor } from './utils';

/**
 * AirdropModal类 - 弹出层插件的主类
 */
export default class AirdropModal {
  private options: Required<AirdropModalOptions>;
  private wrapper: HTMLElement | null = null;
  private modal: HTMLElement | null = null;
  private styleElement: HTMLStyleElement | null = null;
  private countdownInterval: number | null = null;
  private currentState: StateType = 'query';
  private isDragging: boolean = false;
  private startY: number = 0;
  private initialModalHeight: number = 0;
  private currentTranslateY: number = 0;
  
  // 元素引用
  private elements: Record<string, HTMLElement | null> = {
    appLogo: null,
    appName: null,
    projectDesc: null,
    timelineStatusSection: null,
    timelineProgress: null,
    daysValue: null,
    hoursValue: null,
    minutesValue: null,
    secondsValue: null,
    queryState: null,
    loadingState: null,
    successState: null,
    failureState: null,
    addressInput: null,
    
    loadingAddressInput: null,
    connectWalletBtn: null,
    queryButton: null,
    claimAmountToken: null,
    claimAmountUsd: null,
    claimButton: null,
    recheckButton: null,
    successParticles: null,
    loadingOverlay: null,
    footerText: null
  };

  /**
   * 默认选项
   */
  // @ts-ignore - 禁用类型检查，确保编译不会报错
  private static readonly DEFAULT_OPTIONS = {
    appName: 'Airdrop Checker',
    appLogo: 'https://placehold.co/48x48/1D4ED8/FFFFFF?text=AC',
    projectDesc: 'This Project is airdropping a total of 1,000,000 $TOKEN to eligible users.',
    coinSymbol: '$TOKEN',
    endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(), // 30天后
    darkMode: false,
    accentTheme: 'theme-web3',
    onOpen: () => {},
    onClose: () => {},
    onCheck: async () => ({ isEligible: Math.random() > 0.5, amount: '123.45', usdValue: '12.34' }),
    onClaim: async () => true,
    onConnectWallet: async () => '0x' + '1'.repeat(40),
    parent: document.body,
    enableDragOnMobile: true,
    autoInit: true
  } as unknown as Required<AirdropModalOptions>;

  /**
   * 构造函数
   * @param options 配置选项
   */
  constructor(options: AirdropModalOptions = {}) {
    // 合并选项
    this.options = deepMerge(AirdropModal.DEFAULT_OPTIONS, options) as Required<AirdropModalOptions>;
    
    // 初始化
    if (this.options.autoInit) {
      this.init();
    }
  }

  /**
   * 初始化弹出层
   */
  public init(): void {
    // 加载样式
    this.loadStyles();
    
    // 创建DOM
    this.createModal();
    
    // 获取元素引用
    this.getElements();
    
    // 应用选项
    this.applyOptions();
    
    // 初始化倒计时
    this.startCountdown();
    
    // 绑定事件
    this.bindEvents();
  }

  /**
   * 加载样式
   */
  private loadStyles(): void {
    // 创建样式元素
    this.styleElement = injectCSS(`${fontsImport}\n${baseStyles}`);
  }

  /**
   * 创建模态窗口DOM
   */
  private createModal(): void {
    // 创建临时容器
    const tempContainer = document.createElement('div');
    tempContainer.innerHTML = modalTemplate;
    
    // 获取模态窗口元素
    this.wrapper = tempContainer.firstElementChild as HTMLElement;
    this.modal = this.wrapper?.querySelector('#airdrop-checker-modal') as HTMLElement;
    
    // 添加到父元素
    if (this.wrapper && this.options.parent) {
      this.options.parent.appendChild(this.wrapper);
    }
  }

  /**
   * 获取元素引用
   */
  private getElements(): void {
    if (!this.wrapper) return;
    
    this.elements = {
      appLogo: this.wrapper.querySelector('#airdrop-modal-app-logo'),
      appName: this.wrapper.querySelector('#airdrop-modal-app-name'),
      projectDesc: this.wrapper.querySelector('#airdrop-modal-project-desc-text'),
      timelineStatusSection: this.wrapper.querySelector('#airdrop-modal-timeline-status-section'),
      timelineProgress: this.wrapper.querySelector('#airdrop-modal-timeline-progress'),
      daysValue: this.wrapper.querySelector('#airdrop-modal-days-value'),
      hoursValue: this.wrapper.querySelector('#airdrop-modal-hours-value'),
      minutesValue: this.wrapper.querySelector('#airdrop-modal-minutes-value'),
      secondsValue: this.wrapper.querySelector('#airdrop-modal-seconds-value'),
      queryState: this.wrapper.querySelector('#airdrop-modal-query-state'),
      loadingState: this.wrapper.querySelector('#airdrop-modal-loading-state'),
      successState: this.wrapper.querySelector('#airdrop-modal-success-state'),
      failureState: this.wrapper.querySelector('#airdrop-modal-failure-state'),
      addressInput: this.wrapper.querySelector('#airdrop-modal-address-input'),
      loadingAddressInput: this.wrapper.querySelector('#airdrop-modal-loading-address-input'),
      connectWalletBtn: this.wrapper.querySelector('#airdrop-modal-connect-wallet-btn'),
      queryButton: this.wrapper.querySelector('#airdrop-modal-query-button'),
      claimAmountToken: this.wrapper.querySelector('#airdrop-modal-claim-amount-token'),
      claimAmountUsd: this.wrapper.querySelector('#airdrop-modal-claim-amount-usd'),
      claimButton: this.wrapper.querySelector('#airdrop-modal-claim-button'),
      recheckButton: this.wrapper.querySelector('#airdrop-modal-recheck-button'),
      successParticles: this.wrapper.querySelector('#airdrop-modal-success-particles'),
      loadingOverlay: this.wrapper.querySelector('#airdrop-modal-loading-overlay'),
      footerText: this.wrapper.querySelector('#airdrop-modal-footer-text')
    };
  }

  /**
   * 应用选项
   */
  private applyOptions(): void {
    // 应用暗色模式
    if (this.options.darkMode) {
      document.documentElement.classList.add('airdrop-modal-dark');
    }
    
    // 应用主题
    this.applyTheme(this.options.accentTheme);
    
    // 设置基本信息
    if (this.elements.appName) {
      this.elements.appName.textContent = this.options.appName;
    }
    
    if (this.elements.appLogo) {
      (this.elements.appLogo as HTMLImageElement).src = this.options.appLogo;
    }
    
    if (this.elements.projectDesc) {
      this.elements.projectDesc.textContent = this.options.projectDesc;
    }
    
    if (this.elements.footerText) {
      this.elements.footerText.textContent = `Powered by ${this.options.appName}`;
    }
    
    // 更新时间线进度
    this.updateTimelineProgress();
  }

  /**
   * 更新时间线进度显示
   */
  private updateTimelineProgress(): void {
    const timelineProgress = this.elements.timelineProgress;
    if (!timelineProgress) {
        console.warn('Timeline progress element not found');
        return;
    }
    
    // 计算进度百分比
    const startDate = new Date('2023-05-01').getTime(); // 示例开始日期
    const endDate = new Date(this.options.endDate).getTime();
    const currentDate = new Date().getTime();
    
    // 检查日期是否有效
    if (isNaN(startDate) || isNaN(endDate) || isNaN(currentDate)) {
        console.warn('Invalid date values for timeline progress calculation');
        return;
    }
    
    let progressPercentage = 0;
    if (currentDate >= startDate) {
        if (currentDate < endDate) {
            progressPercentage = ((currentDate - startDate) / (endDate - startDate)) * 100;
        } else {
            progressPercentage = 100;
        }
    }
    
    // 设置进度条宽度
    timelineProgress.style.width = `47%`;
    console.log(`Timeline progress set to ${progressPercentage.toFixed(1)}%`);
    
    // 确保也设置背景色
    const themeKey = this.options.accentTheme as keyof typeof DEFAULT_THEMES;
    const themeColors = DEFAULT_THEMES[themeKey];
    
    if (themeColors) {
        timelineProgress.style.backgroundColor = themeColors.primary.DEFAULT;
    }
  }

  /**
   * 更新时间线节点状态
   * @param progressPercentage 进度百分比
   */
  private updateTimelineNodeStates(progressPercentage: number): void {
    if (!this.modal) return;
    
    const timelineNodes = this.modal.querySelectorAll('.airdrop-modal-timeline-node');
    if (!timelineNodes || timelineNodes.length === 0) return;
    
    // 清除当前状态
    timelineNodes.forEach(node => {
        node.classList.remove('active', 'completed');
    });
    
    // 设置新状态
    if (progressPercentage >= 0 && timelineNodes.length > 0) {
        (timelineNodes[0] as HTMLElement).classList.add('completed');
    }
    
    if (progressPercentage < 100 && progressPercentage >= 0 && timelineNodes.length > 1) {
        (timelineNodes[1] as HTMLElement).classList.add('active');
    } else if (progressPercentage >= 100 && timelineNodes.length > 2) {
        if (timelineNodes[1]) (timelineNodes[1] as HTMLElement).classList.add('completed');
        if (timelineNodes[2]) (timelineNodes[2] as HTMLElement).classList.add('completed');
    }
    
    // 根据主题色设置时间线颜色
    this.applyTimelineColors();
  }

  /**
   * 应用时间线颜色
   */
  private applyTimelineColors(): void {
    if (!this.modal) return;
    
      const themeKey = this.options.accentTheme as keyof typeof DEFAULT_THEMES;
      const themeColors = DEFAULT_THEMES[themeKey];
      
      if (!themeColors) return;
      
    // 设置进度条颜色
    const timelineProgress = this.elements.timelineProgress;
    if (timelineProgress) {
        timelineProgress.style.backgroundColor = themeColors.primary.DEFAULT;
    }
    
    // 设置活动节点颜色
    const activeNode = this.modal.querySelector('.airdrop-modal-timeline-node.active');
    if (activeNode) {
        (activeNode as HTMLElement).style.color = themeColors.primary.DEFAULT;
    }
    
    // 设置完成节点颜色
    const completedNodes = this.modal.querySelectorAll('.airdrop-modal-timeline-node.completed');
    completedNodes.forEach(node => {
        (node as HTMLElement).style.color = themeColors.primary.DEFAULT;
    });
  }

  /**
   * 应用主题
   * @param themeName 主题名称
   */
  private applyTheme(themeName: string): void {
    if (!this.wrapper) return;
    
    // 移除所有主题类
    Object.keys(DEFAULT_THEMES).forEach(theme => {
      this.wrapper?.classList.remove(`airdrop-modal-${theme}`);
    });
    
    // 添加新主题类
    this.wrapper.classList.add(`airdrop-modal-${themeName}`);
    
    // 设置自定义属性
    this.setCSSVariablesForTheme(themeName);
    
    // 应用主题颜色
    const themeKey = themeName as keyof typeof DEFAULT_THEMES;
    const themeColors = DEFAULT_THEMES[themeKey];
    if (themeColors) {
      this.applyThemeColors(themeColors);
      
      // 更新项目描述背景 - 处理多种可能的选择器
      this.updateProjectDescBg(themeName);
    }
  }

  /**
   * 设置主题的CSS变量
   * @param themeName 主题名称
   */
  private setCSSVariablesForTheme(themeName: string): void {
    const root = document.documentElement;
    const themeKey = themeName as keyof typeof DEFAULT_THEMES;
    const themeColors = DEFAULT_THEMES[themeKey];
    
    if (!themeColors) {
      console.error(`主题 ${themeName} 不存在，使用默认主题`);
      return;
    }
    
    const primaryRgb = themeColors.primary.rgb || '37, 99, 235';
    const particleColor = themeColors.success.particle || '#34D399';
    
    
    root.style.setProperty('--particle-color', particleColor);
    root.style.setProperty('--pulse-node-color-alpha', `rgba(${primaryRgb}, 0.4)`);
    
    const isDark = document.documentElement.classList.contains('airdrop-modal-dark');
    const primaryShadow = themeColors.primary.shadow || (isDark ? 'rgba(0,0,0,0.3)' : 'rgba(0,0,0,0.1)');
    const secondaryShadow = themeColors.secondary?.shadow || (isDark ? 'rgba(0,0,0,0.2)' : 'rgba(0,0,0,0.05)');
    
    root.style.setProperty('--card-shadow-color-1', primaryShadow);
    root.style.setProperty('--card-shadow-color-2', secondaryShadow);
    root.style.setProperty('--card-shadow-color-1-dark', primaryShadow);
    root.style.setProperty('--card-shadow-color-2-dark', secondaryShadow);
    
    // 设置背景色和文本颜色
    this.applyThemeColors(themeColors);
  }
  
  /**
   * 应用主题颜色
   * @param themeColors 主题颜色配置
   */
  private applyThemeColors(themeColors: ThemeConfig): void {
    if (!this.wrapper || !this.modal) return;
    
    const isDark = document.documentElement.classList.contains('airdrop-modal-dark');
    
    // 基础颜色
    const baseColors = {
      pageBg: isDark ? '#0B1120' : '#F3F4F6',
      surfaceBg: isDark ? '#1F2937' : '#FFFFFF',
      textColor: isDark ? '#F3F4F6' : '#111827',
      secondaryTextColor: isDark ? '#9CA3AF' : '#4B5563',
      borderColor: isDark ? '#374151' : '#E5E7EB',
      disabledBg: isDark ? '#374151' : '#F3F4F6',
      disabledText: isDark ? '#6B7280' : '#9CA3AF',
      loaderBorderGeneric: isDark ? '#4B5563' : '#E5E7EB',
    };
    
    // 设置基础样式
    document.body.style.margin = '0';

    document.body.style.fontFamily = "'Inter', sans-serif";
    
    // 设置遮罩层背景色 - 修改这里，使用半透明黑色或白色
    if (this.wrapper) {
      this.wrapper.style.backgroundColor = isDark 
        ? 'rgba(0, 0, 0, 0.75)' 
        : 'rgba(0, 0, 0, 0.5)';
    }
    
    // 设置模态窗口背景色和边框 - 确保这里使用不同的颜色
    if (this.modal) {
      this.modal.style.backgroundColor = baseColors.surfaceBg;
      this.modal.style.color = baseColors.textColor;
      this.modal.style.borderColor = baseColors.borderColor;
      // 添加阴影以增强区分度
      this.modal.style.boxShadow = isDark 
        ? '0 10px 25px -5px rgba(0, 0, 0, 0.5), 0 8px 10px -6px rgba(0, 0, 0, 0.3)' 
        : '0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.05)';
    }
    
    // 设置头部样式
    const modalHeader = this.modal.querySelector('.airdrop-modal-header');
    if (modalHeader) {
      (modalHeader as HTMLElement).style.borderColor = baseColors.borderColor;
      (modalHeader as HTMLElement).style.backgroundColor = baseColors.surfaceBg;
    }
    
    const appName = this.elements.appName;
    if (appName) {
      appName.style.color = baseColors.textColor;
    }
    
    const handleBg = this.modal.querySelector('.airdrop-modal-handle-bg');
    if (handleBg) {
      (handleBg as HTMLElement).style.backgroundColor = baseColors.surfaceBg;
    }
    
    const handleIndicator = this.modal.querySelector('.airdrop-modal-handle-indicator');
    if (handleIndicator) {
      (handleIndicator as HTMLElement).style.backgroundColor = isDark ? '#4A5562' : '#D1D5DB';
    }
    
    // 设置项目描述背景
    const projectDescBg = this.modal.querySelector('.airdrop-modal-project-desc');
    if (projectDescBg) {
      (projectDescBg as HTMLElement).style.backgroundColor = themeColors.secondary.DEFAULT;
      (projectDescBg as HTMLElement).style.color = themeColors.secondary.textOn || baseColors.secondaryTextColor;
    }
    
    // 设置时间线
    const timelineProgress = this.modal.querySelector('#airdrop-modal-timeline-progress');
    if (timelineProgress) {
        (timelineProgress as HTMLElement).style.backgroundColor = themeColors.primary.DEFAULT;
        console.log(`Updated timeline progress color to ${themeColors.primary.DEFAULT}`);
    }
    
    const timelineConnector = this.modal.querySelector('.airdrop-modal-timeline-connector');
    if (timelineConnector) {
      (timelineConnector as HTMLElement).style.backgroundColor = baseColors.borderColor;
    }
    
    const timelineNodes = this.modal.querySelectorAll('.airdrop-modal-timeline-node');
    if (timelineNodes) {
      timelineNodes.forEach(node => {
        (node as HTMLElement).style.borderColor = baseColors.borderColor;
        if ((node as HTMLElement).classList.contains('active')) {
          (node as HTMLElement).style.color = themeColors.primary.DEFAULT;
        } else {
          (node as HTMLElement).style.color = baseColors.secondaryTextColor;
        }
      });
    }
    
    const timelineLabels = this.modal.querySelectorAll('.airdrop-modal-timeline-label');
    if (timelineLabels) {
      timelineLabels.forEach(label => {
        (label as HTMLElement).style.color = baseColors.secondaryTextColor;
      });
    }
    
    const timelineDates = this.modal.querySelectorAll('.airdrop-modal-timeline-date');
    if (timelineDates) {
      timelineDates.forEach(date => {
        (date as HTMLElement).style.color = isDark ? '#6B7280' : '#9CA3AF';
      });
    }
    
    // 设置状态卡片
    const statusCard = this.modal.querySelector('.airdrop-modal-status-card');
    if (statusCard) {
      (statusCard as HTMLElement).className = `airdrop-modal-status-card p-5 rounded-xl space-y-4 shadow-lg ${isDark ? '' : 'bg-gray-50'}`;
      if (isDark) {
        (statusCard as HTMLElement).style.backgroundColor = baseColors.surfaceBg;
      }
    }
    
    const statusText = this.modal.querySelector('.airdrop-modal-status-text');
    if (statusText) {
      (statusText as HTMLElement).style.color = baseColors.textColor;
    }
    
    const statusTag = this.modal.querySelector('.airdrop-modal-status-tag');
    if (statusTag) {
      (statusTag as HTMLElement).style.backgroundColor = `rgba(${hexToRgb(themeColors.success.DEFAULT)}, 0.2)`;
      (statusTag as HTMLElement).style.color = themeColors.success.DEFAULT;
    }
    
    const statusIndicator = this.modal.querySelector('.airdrop-modal-status-indicator');
    if (statusIndicator) {
      (statusIndicator as HTMLElement).style.backgroundColor = themeColors.success.DEFAULT;
    }
    
    // 设置倒计时
    const countdownLabel = this.modal.querySelector('.airdrop-modal-countdown-label');
    if (countdownLabel) {
      (countdownLabel as HTMLElement).style.color = baseColors.secondaryTextColor;
    }
    
    const countdownValue = this.modal.querySelector('.airdrop-modal-countdown-value');
    if (countdownValue) {
      (countdownValue as HTMLElement).style.color = baseColors.textColor;
    }
    
    // 设置倒计时单位
    const countdownUnits = this.modal.querySelectorAll('.airdrop-modal-countdown-unit');
    if (countdownUnits) {
      countdownUnits.forEach(unit => {
        (unit as HTMLElement).style.backgroundColor = isDark ? baseColors.borderColor : '#E5E7EB';
      });
    }
    
    const countdownUnitLabels = this.modal.querySelectorAll('.airdrop-modal-countdown-unit-label');
    if (countdownUnitLabels) {
      countdownUnitLabels.forEach(label => {
        (label as HTMLElement).style.color = baseColors.secondaryTextColor;
      });
    }
    
    // 设置地址输入框
    if (this.elements.addressInput) {
      this.elements.addressInput.style.backgroundColor = baseColors.surfaceBg;
      this.elements.addressInput.style.color = baseColors.textColor;
      this.elements.addressInput.style.borderColor = baseColors.borderColor;
      this.elements.addressInput.style.outline = 'none';
      this.elements.addressInput.style.boxShadow = 'none';
    }
    
    // 设置连接钱包按钮
    if (this.elements.connectWalletBtn) {
      this.elements.connectWalletBtn.style.color = themeColors.primary.DEFAULT;
      this.elements.connectWalletBtn.classList.add(isDark ? 'hover:bg-gray-700' : 'hover:bg-blue-100');
    }
    
    // 设置查询按钮颜色
    const queryButton = this.elements.queryButton;
    if (queryButton) {
      queryButton.style.backgroundColor = themeColors.primary.DEFAULT;
      queryButton.style.color = themeColors.primary.textOn || '#FFFFFF';
    }
    
    // 设置加载状态
    const loadingAddressInput = this.modal.querySelector('#loading-address-input');
    if (loadingAddressInput) {
      (loadingAddressInput as HTMLElement).style.backgroundColor = baseColors.disabledBg;
      (loadingAddressInput as HTMLElement).style.color = baseColors.disabledText;
      (loadingAddressInput as HTMLElement).style.borderColor = baseColors.borderColor;
    }
    
    const loadingBtn = this.modal.querySelector('#loading-state button');
    if (loadingBtn) {
      (loadingBtn as HTMLElement).style.backgroundColor = baseColors.disabledBg;
      const disabledBtnText = loadingBtn.querySelector('.disabled-btn-text-color');
      if (disabledBtnText) {
        (disabledBtnText as HTMLElement).style.color = baseColors.disabledText;
      }
    }
    
    const loader = this.modal.querySelector('#loading-state .airdrop-modal-loader');
    if (loader) {
      (loader as HTMLElement).style.borderColor = baseColors.loaderBorderGeneric;
      (loader as HTMLElement).style.borderTopColor = themeColors.primary.DEFAULT;
    }
    
    const loadingText = this.modal.querySelector('#loading-state .airdrop-modal-loading-text');
    if (loadingText) {
      (loadingText as HTMLElement).style.color = baseColors.secondaryTextColor;
    }
    
    // 设置成功状态
    const successCard = this.modal.querySelector('.airdrop-modal-success-card');
    if (successCard) {
      (successCard as HTMLElement).style.backgroundColor = `rgba(${hexToRgb(themeColors.success.DEFAULT)}, 0.15)`;
      (successCard as HTMLElement).style.borderColor = `rgba(${hexToRgb(themeColors.success.DEFAULT)}, 0.3)`;
    }
    
    const successIconOuter = this.modal.querySelector('.airdrop-modal-success-icon-outer');
    if (successIconOuter) {
      (successIconOuter as HTMLElement).style.backgroundColor = `rgba(${hexToRgb(themeColors.success.DEFAULT)}, 0.2)`;
    }
    
    const successIconInner = this.modal.querySelector('.airdrop-modal-success-icon-inner');
    if (successIconInner) {
      (successIconInner as HTMLElement).style.backgroundColor = `rgba(${hexToRgb(themeColors.success.DEFAULT)}, 0.3)`;
    }
    
    const successIcon = this.modal.querySelector('.airdrop-modal-success-icon');
    if (successIcon) {
      (successIcon as HTMLElement).style.color = themeColors.success.DEFAULT;
    }
    
    const successTitle = this.modal.querySelector('.airdrop-modal-success-title');
    if (successTitle) {
      (successTitle as HTMLElement).style.color = themeColors.success.DEFAULT;
    }
    
    const claimDetailsBg = this.modal.querySelector('.airdrop-modal-claim-details-bg');
    if (claimDetailsBg) {
      (claimDetailsBg as HTMLElement).style.backgroundColor = baseColors.surfaceBg;
    }
    
    const claimDetailsLabel = this.modal.querySelector('.airdrop-modal-claim-details-label');
    if (claimDetailsLabel) {
      (claimDetailsLabel as HTMLElement).style.color = baseColors.secondaryTextColor;
    }
    
    const claimDetailsValue = this.modal.querySelector('.airdrop-modal-claim-details-value');
    if (claimDetailsValue) {
      (claimDetailsValue as HTMLElement).style.color = baseColors.textColor;
    }
    
    const claimDetailsUsd = this.modal.querySelector('.airdrop-modal-claim-details-usd');
    if (claimDetailsUsd) {
      (claimDetailsUsd as HTMLElement).style.color = baseColors.secondaryTextColor;
    }
    
    // 设置声明按钮颜色
    const claimButton = this.elements.claimButton;
    if (claimButton) {
      claimButton.style.backgroundColor = themeColors.success.DEFAULT;
      claimButton.style.color = themeColors.success.textOn || '#FFFFFF';
    }
    
    // 设置失败状态
    const failureCard = this.modal.querySelector('.airdrop-modal-failure-card');
    if (failureCard) {
      (failureCard as HTMLElement).style.backgroundColor = `rgba(${hexToRgb(themeColors.error.DEFAULT)}, 0.15)`;
      (failureCard as HTMLElement).style.borderColor = `rgba(${hexToRgb(themeColors.error.DEFAULT)}, 0.3)`;
    }
    
    const failureIcon = this.modal.querySelector('.airdrop-modal-failure-icon');
    if (failureIcon) {
      (failureIcon as HTMLElement).style.color = themeColors.error.DEFAULT;
    }
    
    const failureTitle = this.modal.querySelector('.airdrop-modal-failure-title');
    if (failureTitle) {
      (failureTitle as HTMLElement).style.color = themeColors.error.DEFAULT;
    }
    
    const failureText = this.modal.querySelector('.airdrop-modal-failure-text');
    if (failureText) {
      (failureText as HTMLElement).style.color = baseColors.secondaryTextColor;
    }
    
    // 设置重新检查按钮颜色
    const recheckButton = this.elements.recheckButton;
    if (recheckButton) {
      recheckButton.style.backgroundColor = themeColors.secondary.DEFAULT;
      recheckButton.style.color = themeColors.secondary.textOn || baseColors.secondaryTextColor;
    }
    
    // 设置页脚
    const footer = this.modal.querySelector('.airdrop-modal-footer');
    if (footer) {
      (footer as HTMLElement).style.backgroundColor = baseColors.surfaceBg;
      (footer as HTMLElement).style.borderColor = baseColors.borderColor;
    }
    
    const footerText = this.modal.querySelector('.airdrop-modal-footer-text');
    if (footerText) {
      (footerText as HTMLElement).style.color = baseColors.secondaryTextColor;
    }
  }
  
  /**
   * 显示弹出层
   */
  public show(): void {
    if (!this.wrapper) return;
    
    this.wrapper.classList.remove('airdrop-modal-hidden');
    this.wrapper.classList.add('airdrop-modal-visible');
    
    if (this.modal) {
      if (isMobileDevice()) {
        this.modal.classList.add('airdrop-modal-slide-up-active');
      } else {
        this.modal.classList.add('airdrop-modal-fade-in-active');
      }
    }
    
    // 调用打开回调
    this.options.onOpen();
  }
  
  /**
   * 隐藏弹出层
   */
  public hide(): void {
    if (!this.wrapper || !this.modal) return;
    
    if (isMobileDevice()) {
      this.modal.classList.remove('airdrop-modal-slide-up-active');
    } else {
      this.modal.classList.remove('airdrop-modal-fade-in-active');
    }
    
    setTimeout(() => {
      if (this.wrapper) {
        this.wrapper.classList.add('airdrop-modal-hidden');
        this.wrapper.classList.remove('airdrop-modal-visible');
      }
      
      // 调用关闭回调
      this.options.onClose();
    }, 300);
  }
  
  /**
   * 切换状态
   * @param state 状态类型
   */
  private setState(state: StateType): void {
    if (!this.wrapper) return;
    
    this.currentState = state;
    
    // 隐藏所有状态容器
    ['query', 'loading', 'success', 'failure'].forEach(stateType => {
      const stateEl = this.wrapper?.querySelector(`#airdrop-modal-${stateType}-state`);
      if (stateEl) {
        stateEl.classList.add('airdrop-modal-hidden');
        stateEl.classList.remove('active');
      }
    });
    
    // 显示当前状态容器
    const activeStateEl = this.wrapper.querySelector(`#airdrop-modal-${state}-state`);
    if (activeStateEl) {
      activeStateEl.classList.remove('airdrop-modal-hidden');
      activeStateEl.classList.add('active');
    }
    
    // 特殊处理
    if (state === 'success') {
      this.createParticles();
    }
    
    // 时间线状态处理
    const timelineSection = this.elements.timelineStatusSection;
    if (timelineSection) {
      if (state === 'success' || state === 'failure') {
        timelineSection.classList.add('airdrop-modal-hidden-for-result');
      } else {
        timelineSection.classList.remove('airdrop-modal-hidden-for-result');
      }
    }
    
    // 加载状态处理
    if (this.elements.loadingOverlay) {
      if (state === 'loading') {
        this.elements.loadingOverlay.classList.remove('airdrop-modal-hidden');
        this.elements.loadingOverlay.classList.add('airdrop-modal-flex');
        requestAnimationFrame(() => {
          if (this.elements.loadingOverlay) {
            this.elements.loadingOverlay.style.opacity = '1';
          }
        });
      } else {
        if (this.elements.loadingOverlay) {
          this.elements.loadingOverlay.style.opacity = '0';
          setTimeout(() => {
            if (this.elements.loadingOverlay) {
              this.elements.loadingOverlay.classList.add('airdrop-modal-hidden');
              this.elements.loadingOverlay.classList.remove('airdrop-modal-flex');
            }
          }, 300);
        }
      }
    }
  }
  
  /**
   * 设置主题
   * @param themeName 主题名称
   */
  public setTheme(themeName: string): void {
    try {
        console.log(`Setting theme: ${themeName}`);
        
        // 标准化主题名称 - 移除'theme-'前缀
        const cleanThemeName = themeName.replace(/^theme-/, '');
        console.log(`Normalized theme name: ${cleanThemeName}`);
        
        // 输出可用的主题列表以便调试
        console.log(`Available themes: ${Object.keys(DEFAULT_THEMES).join(', ')}`);
        
        // 检查主题是否存在
        if (Object.keys(DEFAULT_THEMES).includes(cleanThemeName)) {
            this.options.accentTheme = cleanThemeName;
            console.log(`Theme found: ${cleanThemeName}`);
            
            // 直接更新应用Logo
            this.updateLogoForTheme(cleanThemeName);
            
            // 应用主题
            this.applyTheme(cleanThemeName);
            
            // 更新滚动条样式
            this.updateScrollbarStyle(cleanThemeName);
        } else {
            console.error(`Theme '${themeName}' (normalized: '${cleanThemeName}') not found in DEFAULT_THEMES. Available themes: ${Object.keys(DEFAULT_THEMES).join(', ')}`);
        }
        
        // 显示弹窗
        this.show();
    } catch (error) {
        console.error('Error in setTheme method:', error);
    }
  }
  
  /**
   * 更新特定主题的Logo
   * @param themeName 主题名称(不带前缀)
   */
  private updateLogoForTheme(themeName: string): void {
    // 找到logo元素
    const logoElement = document.getElementById('airdrop-modal-app-logo') as HTMLImageElement;
    if (!logoElement) {
        console.warn('Logo element not found');
        return;
    }
    
    // 定义标准化的logo映射
    const standardLogoMap = {
        'web3': 'https://placehold.co/48x48/2563EB/FFFFFF?text=AC&font=inter',
        'cyberpunk': 'https://placehold.co/48x48/00F0FF/0C0C1A?text=CY&font=roboto-mono', 
        'forest': 'https://placehold.co/48x48/228B22/F5FFF5?text=FP&font=inter',
        'sunset': 'https://placehold.co/48x48/FF7F50/FFFFFF?text=SP&font=inter',
        'oceanic': 'https://placehold.co/48x48/00CED1/FFFFFF?text=OP&font=inter', 
        'minty': 'https://placehold.co/48x48/66CDAA/FFFFFF?text=MP&font=inter',
        'royalpurple': 'https://placehold.co/48x48/6A0DAD/FFFFFF?text=RP&font=inter',
        'crimsongold': 'https://placehold.co/48x48/DC143C/FFFFFF?text=CG&font=inter',
        'deepsea': 'https://placehold.co/48x48/1E90FF/FFFFFF?text=DS&font=inter'
    };
    
    // 更新策略1: 使用options.logos
    if (this.options.logos) {
        // 尝试所有可能的键名格式
        const possibleKeys = [
            themeName,              // 例如: 'web3'
            `theme-${themeName}`,   // 例如: 'theme-web3'
        ];
        
        for (const key of possibleKeys) {
            if (this.options.logos[key]) {
                logoElement.src = this.options.logos[key];
                console.log(`Updated logo via options.logos[${key}]: ${this.options.logos[key]}`);
                
                // 更新项目描述背景样式
                this.updateProjectDescBg(themeName);
                
                return; // 成功更新后退出
            }
        }
    }
    
    // 更新策略2: 使用标准映射
    if (standardLogoMap[themeName]) {
        logoElement.src = standardLogoMap[themeName];
        console.log(`Updated logo via standardLogoMap: ${standardLogoMap[themeName]}`);
        
        // 更新项目描述背景样式
        this.updateProjectDescBg(themeName);
        
        return;
    }
    
    console.warn(`Could not find appropriate logo for theme: ${themeName}`);
  }
  
  /**
   * 更新项目描述背景
   * @param themeName 主题名称(不带前缀)
   */
  private updateProjectDescBg(themeName: string): void {
    if (!this.modal) return;
    
    const themeKey = themeName as keyof typeof DEFAULT_THEMES;
    const themeColors = DEFAULT_THEMES[themeKey];
    
    if (!themeColors) return;
    
    // 尝试找到项目描述背景元素
    const projectDescBgElement = this.modal.querySelector('.airdrop-modal-project-desc-bg');
    if (projectDescBgElement instanceof HTMLElement) {
        projectDescBgElement.style.backgroundColor = themeColors.secondary.DEFAULT;
        console.log(`Updated project description background to ${themeColors.secondary.DEFAULT}`);
    }
    
    // 尝试找到项目描述文本元素
    const projectDescTextElement = this.modal.querySelector('.airdrop-modal-project-desc-text-color');
    if (projectDescTextElement instanceof HTMLElement) {
        const textColor = themeColors.secondary.textOn || '#4B5563';
        projectDescTextElement.style.color = textColor;
        console.log(`Updated project description text color to ${textColor}`);
    }
  }
  
  /**
   * 更新滚动条样式
   * @param themeName 主题名称(不带前缀)
   */
  private updateScrollbarStyle(themeName: string): void {
    const themeKey = themeName as keyof typeof DEFAULT_THEMES;
    const themeColors = DEFAULT_THEMES[themeKey];
    
    if (!themeColors) return;
    
    // 创建动态样式
    let styleTag = document.getElementById('airdrop-scrollbar-style');
    if (!styleTag) {
        styleTag = document.createElement('style');
        styleTag.id = 'airdrop-scrollbar-style';
        document.head.appendChild(styleTag);
    }
    
    // 设置滚动条样式
    const scrollbarColor = themeColors.primary.DEFAULT;
    styleTag.textContent = `
        .airdrop-modal-custom-scrollbar::-webkit-scrollbar-thumb { 
            background: ${scrollbarColor} !important; 
        }
    `;
    
    // 更新时间线进度 - 调用现有方法而不是重复定义
    this.updateTimelineProgress();
  }
  
  /**
   * 切换暗色模式
   */
  public toggleDarkMode(): void {
    this.options.darkMode = !this.options.darkMode;
    
    if (this.options.darkMode) {
      document.documentElement.classList.add('airdrop-modal-dark');
    } else {
      document.documentElement.classList.remove('airdrop-modal-dark');
    }
    
    // 重新应用当前主题
    this.applyTheme(this.options.accentTheme);
  }
  
  /**
   * 切换或设置主题
   * @param themeName 主题名称，可选值为 'light', 'dark', 'auto'，或者任何有效的主题名称
   */
  public toggleTheme(themeName: string): void {
    // Handle light/dark mode switching
    if (themeName === 'dark') {
      // Set to dark mode
      if (!this.options.darkMode) {
        this.toggleDarkMode();
      }
    } else if (themeName === 'light') {
      // Set to light mode
      if (this.options.darkMode) {
        this.toggleDarkMode();
      }
    } else if (themeName === 'auto') {
      // Auto mode based on system preference
      const prefersDarkMode = window.matchMedia && 
        window.matchMedia('(prefers-color-scheme: dark)').matches;
      if (this.options.darkMode !== prefersDarkMode) {
        this.toggleDarkMode();
      }
    } else {
      // If not a light/dark mode toggle, try to set the specified theme
      this.setTheme(themeName);
    }
  }

  /**
   * 启动倒计时
   */
  private startCountdown(): void {
    const endDate = new Date(this.options.endDate).getTime();
    
    if (isNaN(endDate)) {
      console.error('Invalid end date:', this.options.endDate);
      return;
    }
    
    const updateDisplay = () => {
      const now = new Date().getTime();
      const distance = endDate - now;
      
      if (distance < 0) {
        if (this.countdownInterval) {
          clearInterval(this.countdownInterval);
          this.countdownInterval = null;
        }
        
        this.updateCountdownValues({
          days: '00',
          hours: '00',
          minutes: '00',
          seconds: '00'
        });
        
        return;
      }
      
      const days = Math.floor(distance / (1000 * 60 * 60 * 24));
      const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
      const seconds = Math.floor((distance % (1000 * 60)) / 1000);
      
      this.updateCountdownValues({
        days: formatNumber(days),
        hours: formatNumber(hours),
        minutes: formatNumber(minutes),
        seconds: formatNumber(seconds)
      });
    };
    
    updateDisplay();
    
    if (this.countdownInterval) {
      clearInterval(this.countdownInterval);
    }
    
    this.countdownInterval = window.setInterval(updateDisplay, 1000);
  }
  
  /**
   * 更新倒计时值
   * @param values 倒计时值
   */
  private updateCountdownValues(values: CountdownInfo): void {
    if (!this.elements.daysValue || !this.elements.hoursValue || !this.elements.minutesValue || !this.elements.secondsValue) {
      return;
    }
    
    this.animateFlip(this.elements.daysValue, values.days);
    this.animateFlip(this.elements.hoursValue, values.hours);
    this.animateFlip(this.elements.minutesValue, values.minutes);
    this.animateFlip(this.elements.secondsValue, values.seconds);
    
    // 修改秒数样式处理 - 保留样式但不影响翻牌效果
    const secondsEl = this.elements.secondsValue;
    if (secondsEl) {
      const themeKey = this.options.accentTheme as keyof typeof DEFAULT_THEMES;
      const themeColors = DEFAULT_THEMES[themeKey];
      
      if (!themeColors) return;
      
      // 不清除类名，只添加需要的类
      if (!secondsEl.classList.contains('airdrop-modal-p-25')) {
        secondsEl.classList.add('airdrop-modal-p-25', 'airdrop-modal-rounded-lg', 'airdrop-modal-shadow-inner');
      }
      
      const endDate = new Date(this.options.endDate).getTime();
      const now = new Date().getTime();
      const distance = endDate - now;
      
      if (distance < 60 * 1000) { // 小于1分钟
        secondsEl.style.backgroundColor = themeColors.error.DEFAULT;
        secondsEl.style.color = themeColors.error.textOn || '#FFFFFF';
        if (!secondsEl.classList.contains('airdrop-modal-font-bold')) {
          secondsEl.classList.add('airdrop-modal-font-bold');
        }
      } else if (distance < 10 * 60 * 1000) { // 小于10分钟
        secondsEl.style.backgroundColor = themeColors.warning.DEFAULT;
        secondsEl.style.color = themeColors.warning.textOn || '#FFFFFF';
        if (!secondsEl.classList.contains('airdrop-modal-font-semibold')) {
          secondsEl.classList.add('airdrop-modal-font-semibold');
        }
      } else {
        secondsEl.style.backgroundColor = '';
        secondsEl.style.color = '';
        if (!secondsEl.classList.contains('airdrop-modal-countdown-unit-bg')) {
          secondsEl.classList.add('airdrop-modal-countdown-unit-bg');
        }
      }
    }
  }
  
  /**
   * 动画翻转元素
   * @param element 元素
   * @param newValue 新值
   */
  private animateFlip(element: HTMLElement, newValue: string): void {
    if (!element || element.textContent === newValue) return;
    
    const flipContainer = element.parentElement;
    if (!flipContainer) return;
    
    if (flipContainer.classList.contains('is-flipping')) return;
    
    flipContainer.classList.add('is-flipping');
    element.classList.add('airdrop-modal-flip-animate');
    element.textContent = newValue;
    
    setTimeout(() => {
      element.classList.remove('airdrop-modal-flip-animate');
      flipContainer.classList.remove('is-flipping');
    }, 480);
  }
  
  /**
   * 创建粒子效果
   */
  private createParticles(): void {
    const container = this.elements.successParticles;
    if (!container) return;
    
    container.innerHTML = '';
    
    const particleColor = getComputedStyle(document.documentElement).getPropertyValue('--particle-color').trim() || '#34D399';
    
    for (let i = 0; i < 25; i++) {
      const particle = document.createElement('div');
      particle.classList.add('airdrop-modal-particle');
      particle.style.backgroundColor = particleColor;
      
      const startX = Math.random() * 70 + 15;
      const startY = Math.random() * 40 + 30;
      
      const angle = Math.random() * Math.PI * 2;
      const distance = Math.random() * 150 + 70;
      const endX = startX + Math.cos(angle) * distance;
      const endY = startY + Math.sin(angle) * distance;
      
      particle.style.setProperty('--start-x', `${startX}%`);
      particle.style.setProperty('--start-y', `${startY}%`);
      particle.style.setProperty('--end-x', `${endX}%`);
      particle.style.setProperty('--end-y', `${endY}%`);
      
      particle.style.animationDelay = `${Math.random() * 1}s`;
      container.appendChild(particle);
    }
  }
  
  /**
   * 绑定事件
   */
  private bindEvents(): void {
    if (!this.wrapper) return;
    
    // 关闭模态窗口事件
    this.wrapper.addEventListener('click', (e) => {
      if (e.target === this.wrapper) {
        this.hide();
      }
    });
    
    // 查询按钮点击事件
    const queryButton = this.elements.queryButton;
    if (queryButton) {
      queryButton.addEventListener('click', () => {
        this.handleQuery();
      });
    }
    
    // 地址输入框回车事件和焦点事件
    const addressInput = this.elements.addressInput;
    if (addressInput) {
      // 回车事件处理
      addressInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
          this.handleQuery();
        }
      });
      
      // 焦点事件处理
      addressInput.addEventListener('focus', () => {
        addressInput.style.outline = 'none';
        addressInput.style.boxShadow = 'none';
        addressInput.style.borderColor = 'rgb(37 99 235 / 1)';
      });
      
      // 失去焦点事件处理
      addressInput.addEventListener('blur', () => {
        const baseColors = {
          borderColor: document.documentElement.classList.contains('airdrop-modal-dark') ? '#374151' : '#E5E7EB',
        };
        addressInput.style.borderColor = baseColors.borderColor;
      });
    }
    
    // 连接钱包按钮点击事件
    const connectWalletBtn = this.elements.connectWalletBtn;
    if (connectWalletBtn) {
      connectWalletBtn.addEventListener('click', () => {
        this.handleConnectWallet();
      });
    }
    
    // 声明按钮点击事件
    const claimButton = this.elements.claimButton;
    if (claimButton) {
      claimButton.addEventListener('click', () => {
        this.handleClaim();
      });
    }
    
    // 重新检查按钮点击事件
    const recheckButton = this.elements.recheckButton;
    if (recheckButton) {
      recheckButton.addEventListener('click', () => {
        this.setState('query');
        if (this.elements.addressInput) {
          (this.elements.addressInput as HTMLInputElement).value = '';
          this.elements.addressInput.focus();
        }
      });
    }
    
    // 移动端拖拽处理
    if (this.options.enableDragOnMobile && isMobileDevice()) {
      this.setupDragHandler();
    }
  }
  
  /**
   * 模拟API调用检查地址
   * @param address 要检查的钱包地址
   * @returns Promise<API响应>
   */
  private async mockCheckAddressAPI(address: string): Promise<any> {
    console.log('调用API检查地址:', address);
    
    // 定义API端点
    const apiUrl = '/api/v1/check';
    
    try {
      // 构建请求体
      const requestBody = {
        address: address,
        uuids: ["project-123", "project-456"] // 示例项目UUID列表
      };
      
      console.log(`发送请求到 ${apiUrl}:`, requestBody);
      
      // 模拟网络延迟
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      // 模拟API响应 - 在真实环境中，这里会使用 fetch 发送请求
      // const response = await fetch(apiUrl, {
      //   method: 'POST',
      //   headers: {
      //     'Content-Type': 'application/json'
      //   },
      //   body: JSON.stringify(requestBody)
      // });
      // 
      // if (!response.ok) {
      //   throw new Error(`API请求失败: ${response.status}`);
      // }
      // 
      // const responseData = await response.json();
      
      // 随机决定是否符合条件 (70%概率符合)
      const isEligible = Math.random() > 0.3;
      
      // 模拟API响应格式
      const responseData = {
        success: true,
        data: {
          address: address,
          anyHolding: isEligible,
          projects: [
            {
              name: "测试项目1",
              uuid: "project-123",
              holdingStatus: isEligible,
              details: {
                erc20: [
                  {
                    token: "0x1234567890abcdef1234567890abcdef12345678",
                    holds: isEligible
                  }
                ],
                erc721: [],
                erc1155: []
              }
            },
            {
              name: "测试项目2",
              uuid: "project-456",
              holdingStatus: isEligible,
              details: {
                erc20: [
                  {
                    token: "0xabcdef1234567890abcdef1234567890abcdef12",
                    holds: isEligible
                  }
                ],
                erc721: [],
                erc1155: []
              }
            }
          ],
          chainStatus: {
            "1": "success", // 以太坊主网
            "56": "success"  // 币安智能链
          },
          timestamp: new Date().toISOString()
        }
      };
      
      console.log('API响应:', responseData);
      return responseData;
    } catch (error) {
      console.error('API请求失败:', error);
      throw error;
    }
  }

  /**
   * 处理查询操作
   */
  private async handleQuery(): Promise<void> {
    const addressInput = this.elements.addressInput;
    const queryButton = this.elements.queryButton;
    if (!addressInput || !queryButton) return;
    
    const address = (addressInput as HTMLInputElement).value.trim();
    
    // 简单验证地址
    if (!address || !address.startsWith('0x') || address.length !== 42) {
      // 显示错误样式
      addressInput.classList.add('airdrop-modal-error-border');
      
      // 获取主题颜色
      const themeKey = this.options.accentTheme as keyof typeof DEFAULT_THEMES;
      const themeColors = DEFAULT_THEMES[themeKey];
      
      if (themeColors) {
        addressInput.style.borderColor = themeColors.error.DEFAULT;
      }
      
      setTimeout(() => {
        addressInput.classList.remove('airdrop-modal-error-border');
        addressInput.style.borderColor = '';
      }, 2000);
      
      return;
    }
    
    // 禁用按钮并显示加载状态
    (queryButton as HTMLButtonElement).disabled = true;
    const originalContent = queryButton.innerHTML;
    const originalStyle = queryButton.getAttribute('style') || '';
    
    // 创建包含加载器和文本的容器
    const container = document.createElement('div');
    container.style.display = 'flex';
    container.style.alignItems = 'center';
    container.style.justifyContent = 'center';
    container.style.width = '100%';
    
    // 显示加载状态
    const loaderDiv = document.createElement('div');
    loaderDiv.className = 'airdrop-modal-loader';
    loaderDiv.style.borderColor = 'rgba(156, 163, 175, 0.3)';
    loaderDiv.style.borderTopColor = 'rgb(156, 163, 175)';
    loaderDiv.style.width = '24px';
    loaderDiv.style.height = '24px';
    loaderDiv.style.marginRight = '10px';
    
    const textSpan = document.createElement('span');
    textSpan.textContent = 'Checking...';
    
    container.appendChild(loaderDiv);
    container.appendChild(textSpan);
    
    queryButton.innerHTML = '';
    queryButton.appendChild(container);
    
    // 添加提示文字
    const statusMessage = document.createElement('p');
    statusMessage.textContent = 'Fetching data from the blockchain, please wait.';
    statusMessage.style.textAlign = 'center';
    statusMessage.style.marginTop = '8px';
    statusMessage.style.fontSize = '14px';
    statusMessage.style.color = '#6B7280';
    
    queryButton.parentElement?.appendChild(statusMessage);
    
    try {
      // 设置加载状态地址
      if (this.elements.loadingAddressInput) {
        (this.elements.loadingAddressInput as HTMLInputElement).value = address;
      }
      
      // 调用API检查地址 - 替换原来的options.onCheck调用
      const apiResponse = await this.mockCheckAddressAPI(address);
      
      // 根据API响应格式转换为原来期望的结果格式
      const result = {
        isEligible: apiResponse.data.anyHolding,
        // 如果有多个项目，我们可以汇总总代币数量
        amount: apiResponse.data.anyHolding ? "123.45" : "0", // 示例金额
        usdValue: apiResponse.data.anyHolding ? "12.34" : "0"  // 示例USD价值
      };
      
      // 控制台输出详细的结果数据，便于调试
      console.log('检查结果:', {
        地址: apiResponse.data.address,
        是否符合: apiResponse.data.anyHolding,
        项目数量: apiResponse.data.projects.length,
        链状态: apiResponse.data.chainStatus
      });
      
      // 移除提示文字
      if (statusMessage.parentElement) {
        statusMessage.parentElement.removeChild(statusMessage);
      }
      
      // 不要完全恢复按钮状态，只恢复内容和启用状态
      queryButton.innerHTML = originalContent;
      (queryButton as HTMLButtonElement).disabled = false;
      
      // 根据结果显示相应状态
      if (result.isEligible) {
        // 设置声明金额
        if (this.elements.claimAmountToken) {
          this.elements.claimAmountToken.textContent = `${result.amount} ${this.options.coinSymbol}`;
        }
        
        if (this.elements.claimAmountUsd) {
          this.elements.claimAmountUsd.textContent = `≈ $${result.usdValue} USD`;
        }
        
        this.setState('success');
      } else {
        this.setState('failure');
      }
    } catch (error) {
      console.error('Check error:', error);
      
      // 移除提示文字
      if (statusMessage.parentElement) {
        statusMessage.parentElement.removeChild(statusMessage);
      }
      
      // 不要完全恢复按钮样式，只恢复内容和启用状态
      queryButton.innerHTML = originalContent;
      (queryButton as HTMLButtonElement).disabled = false;
      
      this.setState('failure');
    }
  }
  
  /**
   * 处理连接钱包操作
   */
  private async handleConnectWallet(): Promise<void> {
    const connectWalletBtn = this.elements.connectWalletBtn;
    if (!connectWalletBtn) return;
    
    // 禁用按钮
    (connectWalletBtn as HTMLButtonElement).disabled = true;
    
    // 显示加载状态
    const originalIcon = connectWalletBtn.innerHTML;
    
    // 创建加载器
    const loaderDiv = document.createElement('div');
    loaderDiv.className = 'airdrop-modal-loader';
    loaderDiv.style.borderColor = 'rgba(255, 255, 255, 0.3)';
    loaderDiv.style.borderTopColor = '#FFFFFF';
    loaderDiv.style.width = '24px';
    loaderDiv.style.height = '24px';
    loaderDiv.style.marginRight = '10px';
    
    // 获取主题颜色
    const themeKey = this.options.accentTheme as keyof typeof DEFAULT_THEMES;
    const themeColors = DEFAULT_THEMES[themeKey];
    
    if (themeColors) {
      const isDark = document.documentElement.classList.contains('airdrop-modal-dark');
      const loaderBorderColor = isDark ? '#4B5563' : '#E5E7EB';
      
      loaderDiv.style.borderColor = loaderBorderColor;
      loaderDiv.style.borderTopColor = themeColors.primary.DEFAULT;
    }
    
    connectWalletBtn.innerHTML = '';
    connectWalletBtn.appendChild(loaderDiv);
    
    try {
      // 调用连接钱包回调
      const address = await this.options.onConnectWallet();
      
      // 设置地址
      if (this.elements.addressInput) {
        (this.elements.addressInput as HTMLInputElement).value = address;
        this.elements.addressInput.focus();
      }
    } catch (error) {
      console.error('Connect wallet error:', error);
      alert('Failed to connect wallet. Please try again.');
    } finally {
      // 恢复按钮状态
      (connectWalletBtn as HTMLButtonElement).disabled = false;
      connectWalletBtn.innerHTML = originalIcon;
    }
  }
  
  /**
   * 处理声明操作
   */
  private async handleClaim(): Promise<void> {
    const claimButton = this.elements.claimButton;
    if (!claimButton) return;
    
    // 禁用按钮
    (claimButton as HTMLButtonElement).disabled = true;
    
    // 保存原始内容以便在需要时恢复
    const originalContent = claimButton.innerHTML;
    
    // 创建包含加载器和文本的容器，使用flex布局使内容居中
    const container = document.createElement('div');
    container.style.display = 'flex';
    container.style.alignItems = 'center';
    container.style.justifyContent = 'center';
    container.style.width = '100%';
    
    // 显示加载状态
    const loaderDiv = document.createElement('div');
    loaderDiv.className = 'airdrop-modal-loader';
    loaderDiv.style.borderColor = 'rgba(255, 255, 255, 0.3)';
    loaderDiv.style.borderTopColor = '#FFFFFF';
    loaderDiv.style.width = '24px';
    loaderDiv.style.height = '24px';
    loaderDiv.style.marginRight = '10px';
    
    const textSpan = document.createElement('span');
    textSpan.textContent = 'Processing...';
    
    container.appendChild(loaderDiv);
    container.appendChild(textSpan);
    
    claimButton.innerHTML = '';
    claimButton.appendChild(container);
    
    try {
      // 调用声明回调
      const amount = this.elements.claimAmountToken?.textContent?.split(' ')[0] || '0';
      const success = await this.options.onClaim();
      
      if (success) {
        claimButton.textContent = 'Claimed';
        claimButton.classList.add('airdrop-modal-cursor-not-allowed', 'airdrop-modal-opacity-70');
        
        // 获取主题颜色
        const themeKey = this.options.accentTheme as keyof typeof DEFAULT_THEMES;
        const themeColors = DEFAULT_THEMES[themeKey];
        
        const isDark = document.documentElement.classList.contains('airdrop-modal-dark');
        claimButton.style.backgroundColor = isDark ? '#374151' : '#F3F4F6';
        claimButton.style.color = isDark ? '#6B7280' : '#9CA3AF';
      } else {
        claimButton.textContent = 'Claim Failed, Try Again';
        (claimButton as HTMLButtonElement).disabled = false;
      }
    } catch (error) {
      console.error('Claim error:', error);
      claimButton.textContent = 'Claim Failed, Try Again';
      (claimButton as HTMLButtonElement).disabled = false;
    }
  }
  
  /**
   * 设置移动端拖拽处理
   */
  private setupDragHandler(): void {
    if (!this.modal) return;
    
    const dragIndicator = this.modal.querySelector('.airdrop-modal-sm-block.airdrop-modal-md-hidden');
    if (!dragIndicator) return;
    
    dragIndicator.addEventListener('touchstart', (e: Event) => {
      const touchEvent = e as unknown as TouchEvent;
      if (touchEvent.touches.length !== 1) return;
      
      this.isDragging = true;
      this.startY = touchEvent.touches[0].clientY;
      
      if (this.modal) {
        this.modal.style.transition = 'none';
        this.initialModalHeight = this.modal.offsetHeight;
        this.currentTranslateY = 0;
      }
    }, { passive: true });
    
    dragIndicator.addEventListener('touchmove', (e: Event) => {
      const touchEvent = e as unknown as TouchEvent;
      if (!this.isDragging || touchEvent.touches.length !== 1) return;
      
      const deltaY = touchEvent.touches[0].clientY - this.startY;
      
      if (deltaY > 0) { // 只允许向下拖动
        this.currentTranslateY = deltaY;
        
        if (this.modal) {
          this.modal.style.transform = `translateY(${this.currentTranslateY}px)`;
        }
      }
    }, { passive: true });
    
    dragIndicator.addEventListener('touchend', () => {
      if (!this.isDragging) return;
      
      this.isDragging = false;
      
      if (this.modal) {
        this.modal.style.transition = 'transform 0.3s ease-out';
        
        if (this.currentTranslateY > this.initialModalHeight * 0.3) {
          // 足够远，关闭模态窗口
          this.hide();
        } else {
          // 不够远，恢复位置
          this.modal.style.transform = 'translateY(0)';
        }
      }
    });
  }

  /**
   * 设置弹窗状态
   * @param status 模态框状态
   * @param data 状态相关的数据
   */
  public setStatus(status: ModalStatus, data?: TemplateData): void {
    // 将ModalStatus枚举转换为StateType
    const state: StateType = status.toLowerCase() as StateType;
    
    // 调用私有方法设置状态
    this.setState(state);
    
    // 根据状态和数据进行额外处理
    if (status === ModalStatus.SUCCESS && data) {
      // 设置成功状态相关的数据，比如金额、消息等
      if (data.message && this.elements.successState) {
        const messageElement = this.elements.successState.querySelector('.airdrop-modal-success-message');
        if (messageElement) {
          messageElement.textContent = data.message;
        }
      }
      
      // 如果有倒计时信息
      if (data.countdownTime && this.elements.successState) {
        const countdownElement = this.elements.successState.querySelector('.airdrop-modal-countdown');
        if (countdownElement) {
          countdownElement.textContent = data.countdownTime;
        }
      }
    } else if (status === ModalStatus.FAILURE && data) {
      // 设置失败状态相关的数据，如错误消息
      if (data.message && this.elements.failureState) {
        const messageElement = this.elements.failureState.querySelector('.airdrop-modal-failure-message');
        if (messageElement) {
          messageElement.textContent = data.message;
        }
      }
    }
  }

  /**
   * 重置弹窗状态为初始查询状态
   */
  public reset(): void {
    this.setStatus(ModalStatus.QUERY);
  }

  /**
   * 获取所有可用主题
   * @returns 主题列表
   */
  public getAvailableThemes(): string[] {
    return Object.keys(DEFAULT_THEMES);
  }

    // 使用从utils导入的hexToRgb方法替代此处的私有方法实现

    // 使用从utils导入的shadeColor方法替代此处的私有方法实现
} 